package com.mde.placeholder;

import java.util.List;

import com.mde.placeholder.db.*;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.BufferType;

public class MainActivity extends ListActivity {
	
	public static final String LOGCAT = "placeholder";
	
	ContactsDataSource datasource;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
			
		datasource = new ContactsDataSource(this);
		
	    setContactsList();
	    
	}
	
	private void setContactsList() {
		datasource.openDB();
	    
	    List<Contact> values = datasource.getAllContacts();

	    ArrayAdapter<Contact> adapter = 
	    		new ArrayAdapter<Contact>(this, 
	    				android.R.layout.simple_list_item_1, 
	    				values);
	    setListAdapter(adapter);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	public void choosePosition(View v) {
		Intent intent = new Intent(MainActivity.this, MapActivity.class);
	    startActivityForResult(intent, 1);
	}
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (data == null) {
			Log.i("MAP", "Null data");
			return;
		}
	  
		EditText latIn = (EditText) findViewById(R.id.LatitudeInput);
		EditText lonIn = (EditText) findViewById(R.id.LongitudeInput);
		
		latIn.setText(data.getStringExtra("lat"), BufferType.EDITABLE);
		lonIn.setText(data.getStringExtra("lon"), BufferType.EDITABLE);
		
		Log.i("MAP", "Pressed: " +
				data.getStringExtra("lat") + " " +
				data.getStringExtra("lon")
		);
    }
	
	public void addContact(View v) {
		String username = getUsername();
		String phone = getPhone();
		
		if (phone.contains(" ")) {
			Toast.makeText(this, "Phone number shouldn't contain spaces", 3000).show();
			return;
		}
		
		double lat = getLat();
		double lon = getLon();
		TextView tv = (TextView) this.findViewById(R.id.Title);
		
		if (datasource.insert(username, phone, lat, lon)) {
			tv.setText("Contact succesfully added!");	
			
			ArrayAdapter<Contact> adapter = (ArrayAdapter<Contact>) getListAdapter();
		    
		    adapter.add(new Contact(username, phone, lat, lon));
		    
		    adapter.notifyDataSetChanged();
		    
		} else {
			tv.setText("Contact already exists!");
		}			    
	}
	
	public void checkContact(View v) {
		String username = getUsername();
		TextView tv = (TextView) this.findViewById(R.id.Title);
		
		if (datasource.check(username)) {
			tv.setText("Contact already exists!");	
		} else {
			tv.setText("Contact doesn't exist!");
		}		
	}
	
	public void deleteContact(View v) {
		String username = getUsername();
		TextView tv = (TextView) this.findViewById(R.id.Title);
		
		if (datasource.delete(username)) {
			ArrayAdapter<Contact> adapter = 
					(ArrayAdapter<Contact>) getListAdapter();
			tv.setText("Contact succesfully deleted!");
			for (int i = 0; i < adapter.getCount(); ++i)
		    	if (adapter.getItem(i).getName().equals(username)) {
		    		adapter.remove(adapter.getItem(i));
		    		break;
		    	}
			adapter.notifyDataSetChanged();
		} else {
			tv.setText("Contact doesn't exist!");
		}
	}
	
	private String getUsername() {
		return ((EditText) this.findViewById(R.id.ContactNameInput)).getText().toString();
	}
	
	private String getPhone() {
		return ((EditText) this.findViewById(R.id.ContactPhoneInput)).getText().toString();
	}
	
	private double getLat() {
		return Double.parseDouble(((EditText) this.findViewById(R.id.LatitudeInput)).getText().toString());
	}
	
	private double getLon() {
		return Double.parseDouble(((EditText) this.findViewById(R.id.LongitudeInput)).getText().toString());
	}

	@Override
	protected void onResume() {
		super.onResume();
		datasource.openDB();
	}
	
	@Override 
	protected void onPause() {
		super.onPause();
		datasource.closeDB();
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		//((TextView)findViewById(R.id.Title)).setText(((TextView)v).getText());
		String[] data = ((String)((TextView)v).getText()).split(" ");
		
		//((TextView)findViewById(R.id.Title)).setText(data[2] + " " + data[3]);
		
		double lat = Double.parseDouble(data[data.length - 2]), 
				lon = Double.parseDouble(data[data.length - 1]);
		
		Intent intent = new Intent(MainActivity.this, MapActivity.class);
		StringBuilder name = new StringBuilder();
		for (int i = 0; i < data.length - 3; ++i)
			name.append(data[i]).append(" ");
		intent.putExtra("name", name.toString());
		intent.putExtra("lat", lat);
		intent.putExtra("lon", lon);	

		startActivity(intent);
		
	}    

}
